package com.goldcn.order.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goldcn.common.CommonTools;
import com.goldcn.common.HttpUtil;
import com.goldcn.common.consts.RestConst;
import com.goldcn.common.exception.ServiceException;
import com.goldcn.common.model.DataResult;
import com.goldcn.common.util.CommonUtils;
import com.goldcn.common.util.IdGen;
import com.goldcn.config.ProConstants;
import com.goldcn.goods.service.GoodsService;
import com.goldcn.interceptor.SystemContext;
import com.goldcn.order.dao.*;
import com.goldcn.order.dto.*;
import com.goldcn.order.erpVo.ResultData;
import com.goldcn.order.model.CountOrder;
import com.goldcn.order.vo.*;
import com.goldcn.orderborrow.service.OrderBorrowService;
import com.google.common.base.Strings;
import com.google.common.primitives.Longs;
import com.sun.org.apache.xpath.internal.operations.Bool;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by 1111 on 2016/12/8.
 */
@Service
@Transactional
@ConfigurationProperties("bank")
public class CountOrderService {
    private String classifyUrl;

    public void setClassifyUrl(String classifyUrl) {
        this.classifyUrl = classifyUrl;
    }

    @Autowired
    CountOrderMapper countOrderMapper;

    @Autowired
    CountClassifyMapper countClassifyMapper;

    @Autowired
    OrderInfoMapper orderInfoMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderService orderService;

    @Autowired
    GoodsService goodsService;

    @Autowired
    OrderBankSettlementMapper orderBankSettlementMapper;

    @Autowired
    CommissionDetailMapper commissionDetailMapper;

    @Autowired
    CommissionSettlementMapper commissionSettlementMapper;

    @Autowired
    RestTemplate rest;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    OrderBorrowService orderBorrowService;

    public Object addCountOrder(CountOrder countOrder) {
        countOrder.setId(IdGen.get().nextId());
        countOrder.setTotalAmount((BigDecimal.ZERO));
        countOrder.setOrderCount(0);
        countOrder.setUpdateTime(CommonUtils.getCurTimestamp());
        countOrder.setCompanyID(SystemContext.getCompanyID());
        countOrderMapper.insertSelective(countOrder);
        return "success";
    }

    public Object delteCountOrderByOID(Map<String, Object> params) {
        params.put("companyID", SystemContext.getCompanyID());
        countOrderMapper.deleteByOID(params);
        return "success";
    }

    /**
     * 订单统计表每日数据更新
     *
     * @param startTime
     * @param endTime
     * @return
     */

    public String updateCountOrder(Long startTime, Long endTime) {
        ResultData<List<Map<String, Object>>> result = null;
        try {
            result = restTemplate.getForObject(ProConstants.getAllCompany, ResultData.class);
        } catch (Exception e) {
            throw new ServiceException("获取全部公司信息失败");
        }

        List<Map<String, Object>> sysConfigs = result.getData();
        for (Map<String, Object> m : sysConfigs) {
            String companyInfoID = m.get("companyInfoID").toString();
            updateCountOrderByCompanyID(startTime, endTime, Long.parseLong(companyInfoID));
        }
        return "success";

    }

    private String updateCountOrderByCompanyID(Long startTime, Long endTime, Long companyID) {

        Integer type;
        if (startTime == null || endTime == null) {
            startTime = getTimesamp(1);
            endTime = getTimesamp(2);
            type = 1;
        } else {
            type = 2;
        }
        //得到所有count_order
        List<CountOrder> countOrderList = countOrderMapper.selectAll(companyID);
        if (countOrderList == null || countOrderList.size() == 0) {
            return "";
        }
        Long updateTime = countOrderList.get(0).getUpdateTime();

        switch (type) {
            case 1:   //自动更新则需要判断是否已经更新过
                if (updateTime > getTimesamp(2)) {  //如果大于今天零点
                    throw new ServiceException("今天统计已经更新", RestConst.ErrorCode.FORM_FAIL);
                }
                break;
            case 2:   //手动更新则打印下记录
                System.out.print("手动更新了该时间段的统计:" + startTime + "--" + endTime);
                break;
        }
        //循环所有统计
        for (CountOrder countOrder : countOrderList) {
            OrderCountDto countDto = new OrderCountDto();
            countDto.setStartTime(startTime);
            countDto.setEndTime(endTime);
            if ((countOrder.getId() + "").equals(companyID + "")) {     //所有数据统计
            }
            if ((countOrder.getId() + "").equals(companyID.toString().substring(0, companyID.toString().length() - 1))) {   //总行单独数据统计
                countDto.setBranchID((long) 0);
            }
            //分行单独数据统计
            if (countOrder.getBranchID() != 0 && countOrder.getTwoLevelBranchID() == 0 && countOrder.getSubbranchID() == 0 && countOrder.getSalesManagerID() == 0) {
                countDto.setBranchID(countOrder.getBranchID());
                countDto.setTwoLevelBranchID((long) 0);
                countDto.setSubbranchID((long) 0);
            }
            //二级分行单独数据统计
            if (countOrder.getTwoLevelBranchID() != 0 && countOrder.getSubbranchID() == 0 && countOrder.getSalesManagerID() == 0) {
                countDto.setTwoLevelBranchID(countOrder.getTwoLevelBranchID());
                countDto.setSubbranchID((long) 0);
            }
            //支行单独数据统计
            if (countOrder.getSubbranchID() != 0 && countOrder.getSalesManagerID() == 0) {
                countDto.setSubbranchID(countOrder.getSubbranchID());
            }
            //销售经理单独数据统计
            if (countOrder.getSalesManagerID() != 0) {
                countDto.setSalesManagerID(countOrder.getSalesManagerID());
            }
            countDto.setCompanyID(companyID);
            OrderCountVo orderCountVo = orderInfoMapper.selectOrderCount(countDto);
            countOrder.setOrderCount(countOrder.getOrderCount() + orderCountVo.getOrderQty());
            countOrder.setTotalAmount(countOrder.getTotalAmount().add(orderCountVo.getTransactionTotal() == null ? BigDecimal.ZERO : orderCountVo.getTransactionTotal()));
            countOrder.setUpdateTime(CommonUtils.getCurTimestamp());
            countOrderMapper.updateByPrimaryKeySelective(countOrder);
        }
        return "success";
    }

    /**
     * //分类统计表每日数据更新
     * public Object insertCountClassify(){
     * List<JSONObject> objectList = new ArrayList<>();
     * try {
     * JSONObject jsonObject = rest.getForObject(classifyUrl, JSONObject.class);
     * objectList = jsonObject.getJSONArray("data");
     * }catch (Exception e){
     * throw new ServiceException("调用云管控服务出错",e);
     * }
     * List<ClassifyCountVo> classifyList = orderItemMapper.selectCountByClassify(getTimesamp(1),getTimesamp(2));
     * <p>
     * //已经产生数据的分类ID集合，用于判断
     * List<String> classifyIDList = new ArrayList<>();
     * for(ClassifyCountVo classifyCountVo : classifyList){
     * classifyIDList.add(classifyCountVo.getClassifyID());
     * }
     * <p>
     * Long timesamp = CommonUtils.getCurTimestamp();
     * //未产生数据的分类则销量为0
     * for(JSONObject jsonObject1 : objectList){
     * if(!classifyIDList.contains(jsonObject1.get("clazzid").toString())){
     * CountClassify countClassify = new CountClassify();
     * countClassify.setId(IdGen.get().nextId());
     * countClassify.setAddTime(timesamp);
     * countClassify.setLevel(1);
     * countClassify.setClassifyID(jsonObject1.get("clazzid").toString());
     * countClassify.setClassifyName(jsonObject1.get("clazzname").toString());
     * countClassify.setCount(0);
     * countClassifyMapper.insertSelective(countClassify);
     * }
     * }
     * <p>
     * for(ClassifyCountVo classifyCountVo : classifyList){
     * CountClassify countClassify = new CountClassify();
     * countClassify.setId(IdGen.get().nextId());
     * countClassify.setAddTime(timesamp);
     * countClassify.setLevel(1);
     * countClassify.setClassifyID(classifyCountVo.getClassifyID());
     * countClassify.setClassifyName(classifyCountVo.getClassifyName());
     * countClassify.setCount(classifyCountVo.getCountQty());
     * countClassifyMapper.insertSelective(countClassify);
     * }
     * return "success";
     * }
     */

    //云管控和银行人员pc首页数据
    public Object selectBankHomePageData(Long userID, Long companyID) {
        UserAndCountDto userAndCountDto = (UserAndCountDto) getUserAndCount(userID, 2);
        DashBoardVo dashBoardVo = new DashBoardVo();
        TodoTipsVo todoTipsVo = new TodoTipsVo();
        OrderCountVo orderCountVo = new OrderCountVo();
        OrderCountDto countDtoForInfo = new OrderCountDto(); //查询交易趋势的条件


        // 仪表盘数据【会员、顾问总数】
        //dashBoardVo.setVipUserQty(userAndCountDto.getVipUserQty());
        //dashBoardVo.setConsultantUserQty(userAndCountDto.getConsultantUserQty());


        if (userAndCountDto.getType() == 1) { //管理员
            todoTipsVo.setEmployeeIsAuditQty(userAndCountDto.getEmployeeIsAuditQty());
            if (userAndCountDto.getLevel() == 1) {  //总行
                //CountOrder countOrder = getCountByID((long) 0);   //id为0则是所有订单数据统计
                CountOrder countOrder = getCountByID(SystemContext.getCompanyID());
                //商品数量统计
                Map<String, Object> goodsMap = goodsService.queryUnapproveGoodsNum(null, SystemContext.getCompanyID());
                int shelvesNum = Integer.parseInt(goodsMap.get("shelvesNum") == null ? "0" : goodsMap.get("shelvesNum").toString());
                int UnapproveNum = Integer.parseInt(goodsMap.get("UnapproveNum") == null ? "0" : goodsMap.get("UnapproveNum").toString());
                //资金概况
                //add 总交易额改为销售总额，已结算资金改为商品销售总数，未结算资金改为订单总数，以实时数据为准。
                Map<String, Object> orderSummery = selectOrderSummery(null, null);

                if (orderSummery != null && orderSummery.containsKey("orderQty")) {
                    Long orderQty = (Long) orderSummery.get("orderQty");
                    orderCountVo.setOrderQty(Integer.parseInt(orderQty.toString()));//订单总数
                } else {
                    orderCountVo.setOrderQty(0);//订单总数
                }
                if (orderSummery != null && orderSummery.containsKey("amount")) {
                    orderCountVo.setTransactionTotal(new BigDecimal(orderSummery.get("amount").toString()));  //交易总额
                } else {
                    orderCountVo.setTransactionTotal(BigDecimal.ZERO);
                }
                if (orderSummery != null && orderSummery.containsKey("saleQty")) {
                    orderCountVo.setSalesTotal(new BigDecimal(orderSummery.get("saleQty").toString()));//订单下的商品总数
                } else {
                    orderCountVo.setSalesTotal(BigDecimal.ZERO);//订单下的商品总数

                }

                if (getOffline(companyID) && getOfflinePermission(userID) && orderSummery != null && orderSummery.containsKey("offline")) {
                    Long offlineQty = (Long) orderSummery.get("offline");
                    todoTipsVo.setOfflineIsAuditQty(Integer.parseInt(offlineQty.toString()));//待核销
                } else {
                    todoTipsVo.setOfflineIsAuditQty(0);//待核销

                }


                //orderCountVo.setOrderQty(countOrder.getOrderCount());  //订单总数
                //orderCountVo.setTransactionTotal(countOrder.getTotalAmount());  //交易总额
                BigDecimal settlementTotal = orderService.selectSettlementTotal(null);  //已结算资金
                orderCountVo.setSettlementTotal(settlementTotal == null ? BigDecimal.ZERO : settlementTotal);
                orderCountVo.setNotSettlementTotal(orderCountVo.getTransactionTotal().subtract(orderCountVo.getSettlementTotal())); //未结算资金
                //仪表盘数据
                dashBoardVo.setCompanyQty(userAndCountDto.getCompanyQty());
                dashBoardVo.setOrderQty(countOrder.getOrderCount());
                dashBoardVo.setGoodsOnsaleQty(shelvesNum);
                //待办事项
                todoTipsVo.setCompanyIsAuditQty(userAndCountDto.getCompanyIsAuditQty());
                todoTipsVo.setUserIsAuditQty(userAndCountDto.getUserIsAuditQty());
                todoTipsVo.setGoodsIsAuditQty(UnapproveNum);

                Map<String, String> pointAudit =
                        (Map<String, String>) orderService.getAuditCountByCompanyID(userAndCountDto.getOrganizationalID());

                //提金提现审核 added by tim peng 2017-4-17 == update by lmn 2017-10-18
                JSONObject configJsonObject = getBizConfig(companyID);
                if (getDrawCash(configJsonObject)) {
                    todoTipsVo.setWithDrawCashAuditQty(Integer.valueOf(pointAudit.get("withDrawCashAuditQty")));
                } else {
                    todoTipsVo.setWithDrawCashAuditQty(0);
                }
                if (getDrawGold(configJsonObject)) {
                    todoTipsVo.setWithDrawGoldAuditQty(Integer.valueOf(pointAudit.get("withDrawGoldAuditQty")));
                } else {
                    todoTipsVo.setWithDrawGoldAuditQty(0);
                }

                JSONObject jsonObject = selectUserStatCount(0L, userAndCountDto.getOrganizationalID());
                dashBoardVo.setVipUserQty(jsonObject.getInt("memberCount"));//会员
                dashBoardVo.setConsultantUserQty(jsonObject.getInt("salesCount"));//销售顾问
                dashBoardVo.setSalesManagerQty(jsonObject.getInt("salesManagerID"));//销售经理

            } else {
                OrderCountDto orderCountDto = new OrderCountDto();
                switch (userAndCountDto.getLevel()) {
                    case 2:   //分行
                        orderCountDto.setBranchID(userAndCountDto.getOrganizationalID());
                        countDtoForInfo.setBranchID(userAndCountDto.getOrganizationalID());
                        Map<String, Object> orderSummery = selectOrderSummery("branchID", userAndCountDto.getOrganizationalID());
                        if (orderSummery != null && orderSummery.containsKey("orderQty")) {
                            Long orderQty = (Long) orderSummery.get("orderQty");
                            orderCountVo.setOrderQty(Integer.parseInt(orderQty.toString()));//订单总数
                        } else {
                            orderCountVo.setOrderQty(0);//订单总数
                        }
                        if (orderSummery != null && orderSummery.containsKey("amount")) {
                            orderCountVo.setTransactionTotal(new BigDecimal(orderSummery.get("amount").toString()));  //交易总额
                        } else {
                            orderCountVo.setTransactionTotal(BigDecimal.ZERO);
                        }
                        if (orderSummery != null && orderSummery.containsKey("saleQty")) {
                            orderCountVo.setSalesTotal(new BigDecimal(orderSummery.get("saleQty").toString()));//订单下的商品总数
                        } else {
                            orderCountVo.setSalesTotal(BigDecimal.ZERO);//订单下的商品总数

                        }
                        if (getOffline(companyID) && getOfflinePermission(userID) && orderSummery != null && orderSummery.containsKey("offline")) {
                            Long offlineQty = (Long) orderSummery.get("offline");
                            todoTipsVo.setOfflineIsAuditQty(Integer.parseInt(offlineQty.toString()));//待核销
                        } else {
                            todoTipsVo.setOfflineIsAuditQty(0);//待核销

                        }

                        JSONObject jsonObject = selectUserStatCount(0L, userAndCountDto.getOrganizationalID());
                        dashBoardVo.setVipUserQty(jsonObject.getInt("memberCount"));//会员
                        dashBoardVo.setConsultantUserQty(jsonObject.getInt("salesCount"));//销售顾问
                        dashBoardVo.setSalesManagerQty(jsonObject.getInt("salesManagerID"));//销售经理


                        break;
                    case 3:  //二级分行
                        orderCountDto.setTwoLevelBranchID(userAndCountDto.getOrganizationalID());
                        countDtoForInfo.setTwoLevelBranchID(userAndCountDto.getOrganizationalID());
                        Map<String, Object> orderSummery2 = selectOrderSummery("twoLevelBranchID", userAndCountDto.getOrganizationalID());
                        if (orderSummery2 != null && orderSummery2.containsKey("orderQty")) {
                            Long orderQty2 = (Long) orderSummery2.get("orderQty");
                            orderCountVo.setOrderQty(Integer.parseInt(orderQty2.toString()));//订单总数
                        } else {
                            orderCountVo.setOrderQty(0);//订单总数
                        }
                        if (orderSummery2 != null && orderSummery2.containsKey("amount")) {
                            orderCountVo.setTransactionTotal(new BigDecimal(orderSummery2.get("amount").toString()));  //交易总额
                        } else {
                            orderCountVo.setTransactionTotal(BigDecimal.ZERO);
                        }
                        if (orderSummery2 != null && orderSummery2.containsKey("saleQty")) {
                            orderCountVo.setSalesTotal(new BigDecimal(orderSummery2.get("saleQty").toString()));//订单下的商品总数
                        } else {
                            orderCountVo.setSalesTotal(BigDecimal.ZERO);//订单下的商品总数

                        }
                        if (getOffline(companyID) && getOfflinePermission(userID) && orderSummery2 != null && orderSummery2.containsKey("offline")) {
                            Long offlineQty = (Long) orderSummery2.get("offline");
                            todoTipsVo.setOfflineIsAuditQty(Integer.parseInt(offlineQty.toString()));//待核销
                        } else {
                            todoTipsVo.setOfflineIsAuditQty(0);//待核销

                        }

                        JSONObject jsonObject3 = selectUserStatCount(0L, userAndCountDto.getOrganizationalID());
                        dashBoardVo.setVipUserQty(jsonObject3.getInt("memberCount"));//会员
                        dashBoardVo.setConsultantUserQty(jsonObject3.getInt("salesCount"));//销售顾问
                        dashBoardVo.setSalesManagerQty(jsonObject3.getInt("salesManagerID"));//销售经理
                        break;
                    case 4:  //支行
                        orderCountDto.setSubbranchID(userAndCountDto.getOrganizationalID());
                        countDtoForInfo.setSubbranchID(userAndCountDto.getOrganizationalID());
                        Map<String, Object> orderSummery3 = selectOrderSummery("subbranchID", userAndCountDto.getOrganizationalID());
                        if (orderSummery3 != null && orderSummery3.containsKey("orderQty")) {
                            Long orderQty3 = (Long) orderSummery3.get("orderQty");
                            orderCountVo.setOrderQty(Integer.parseInt(orderQty3.toString()));//订单总数
                        } else {
                            orderCountVo.setOrderQty(0);//订单总数
                        }
                        if (orderSummery3 != null && orderSummery3.containsKey("amount")) {
                            orderCountVo.setTransactionTotal(new BigDecimal(orderSummery3.get("amount").toString()));  //交易总额
                        } else {
                            orderCountVo.setTransactionTotal(BigDecimal.ZERO);
                        }
                        if (orderSummery3 != null && orderSummery3.containsKey("saleQty")) {
                            orderCountVo.setSalesTotal(new BigDecimal(orderSummery3.get("saleQty").toString()));//订单下的商品总数
                        } else {
                            orderCountVo.setSalesTotal(BigDecimal.ZERO);//订单下的商品总数

                        }
                        if (getOffline(companyID) && getOfflinePermission(userID) && orderSummery3 != null && orderSummery3.containsKey("offline")) {
                            Long offlineQty = (Long) orderSummery3.get("offline");
                            todoTipsVo.setOfflineIsAuditQty(Integer.parseInt(offlineQty.toString()));//待核销
                        } else {
                            todoTipsVo.setOfflineIsAuditQty(0);//待核销

                        }
                        JSONObject jsonObject4 = selectUserStatCount(0L, userAndCountDto.getOrganizationalID());
                        dashBoardVo.setVipUserQty(jsonObject4.getInt("memberCount"));//会员
                        dashBoardVo.setConsultantUserQty(jsonObject4.getInt("salesCount"));//销售顾问
                        dashBoardVo.setSalesManagerQty(jsonObject4.getInt("salesManagerID"));//销售经理

                        break;
                }
                //资金概况
                orderCountDto.setSalesManagerID((long) 0);
                //update buyadong 2017年6月7日19:44:14
                //orderCountVo = getOrderCountByCondition(orderCountDto);  //获取总订单量和总交易额

                orderCountDto.setStartTime(getTimesamp(3)); //本周起始时间戳
                orderCountDto.setEndTime(CommonUtils.getCurTimestamp());
                orderCountVo.setWeekTransaction(getTransactionByInfo(orderCountDto) == null ? BigDecimal.ZERO : getTransactionByInfo(orderCountDto));//本周交易总额

                //仪表盘数据
                dashBoardVo.setOrderQty(orderCountVo.getOrderQty());
            }
        } else if (userAndCountDto.getType() == 2) {   //销售经理
            countDtoForInfo.setSalesManagerID(userID);

            OrderCountDto orderCountDto = new OrderCountDto();
            orderCountDto.setSalesManagerID(userID);
            //orderCountVo = getOrderCountByCondition(orderCountDto);  //获取总订单量和总交易额
            Map<String, Object> orderSummery = selectOrderSummery("salesManagerID", userID);
            if (orderSummery != null && orderSummery.containsKey("orderQty")) {
                Long orderQty = (Long) orderSummery.get("orderQty");
                orderCountVo.setOrderQty(Integer.parseInt(orderQty.toString()));//订单总数
            } else {
                orderCountVo.setOrderQty(0);//订单总数
            }
            if (orderSummery != null && orderSummery.containsKey("amount")) {
                orderCountVo.setTransactionTotal(new BigDecimal(orderSummery.get("amount").toString()));  //交易总额
            } else {
                orderCountVo.setTransactionTotal(BigDecimal.ZERO);
            }
            if (orderSummery != null && orderSummery.containsKey("saleQty")) {
                orderCountVo.setSalesTotal(new BigDecimal(orderSummery.get("saleQty").toString()));//订单下的商品总数
            } else {
                orderCountVo.setSalesTotal(BigDecimal.ZERO);//订单下的商品总数
            }

            if (getOffline(companyID) && getOfflinePermission(userID) && orderSummery != null && orderSummery.containsKey("offline")) {
                Long offlineQty = (Long) orderSummery.get("offline");
                todoTipsVo.setOfflineIsAuditQty(Integer.parseInt(offlineQty.toString()));//待核销
            } else {
                todoTipsVo.setOfflineIsAuditQty(0);//待核销

            }
            orderCountDto.setStartTime(getTimesamp(3)); //本周起始时间戳
            orderCountDto.setEndTime(CommonUtils.getCurTimestamp());
            orderCountVo.setWeekTransaction(getTransactionByInfo(orderCountDto));//本周交易总额

            //仪表盘数据
            dashBoardVo.setOrderQty(orderCountVo.getOrderQty());

            //待办事项
            todoTipsVo.setUserIsAuditQty(userAndCountDto.getUserIsAuditQty()); //会员审核数量

            JSONObject jsonObject = selectUserStatCount(userID, userAndCountDto.getOrganizationalID());
            dashBoardVo.setVipUserQty(jsonObject.getInt("memberCount"));//会员
            dashBoardVo.setConsultantUserQty(jsonObject.getInt("salesCount"));//销售顾问
            dashBoardVo.setSalesManagerQty(jsonObject.getInt("salesManagerID"));//销售经理

        }
        countDtoForInfo.setStartTime(getTimesamp(4));
        countDtoForInfo.setEndTime(getTimesamp(2) - 1);
        Map<Long, BigDecimal> transactionTrend = getTransactionTrend1(countDtoForInfo);


        if (null != companyID) {//借货未审核数量
            userAndCountDto.setCompanyID(companyID);
            Integer noAuditNum = 0;
            if ("2".equals(getBorrowSW(companyID))) {//借货开启
                noAuditNum = orderBorrowService.getNoAuditNum(userID, companyID, userAndCountDto.getLevel());
            }
            todoTipsVo.setBorrowAuditQty(noAuditNum);
        }

        Map<String, Object> mapObject = new HashMap<>();
        mapObject.put("FundProfile", orderCountVo);
        mapObject.put("DashBoardVo", dashBoardVo);
        mapObject.put("TodoTipsVo", todoTipsVo);
        mapObject.put("transactionTrend", transactionTrend);
        return mapObject;
    }


    private Map<String, Object> selectOrderSummery(String type, Long value) {
        Map<String, Object> map = new HashMap<>();
        if (type != null && value != null) {
            map.put("type", type);
            map.put("value", value);
        }
        map.put("companyID", SystemContext.getCompanyID());
        return orderInfoMapper.selectOrderSummery(map);
    }

    /**
     * 获取借货功能开关
     *
     * @param companyID
     * @return
     */
    private String getBorrowSW(Long companyID) {
        DataResult result = HttpUtil.httpGet(
                ProConstants.getOrderBorrowSW + companyID, restTemplate);
        return (result != null && com.google.common.base.Objects.equal(1, result.getIsSuccess()) && result.getData() != null) ?
                result.getData().toString() : "";
    }

    /**
     * 获取线下订单开关
     */
    private Boolean getOffline(Long companyID) {
        DataResult result = HttpUtil.httpGet(ProConstants.getBizConfig + companyID, restTemplate);
        if (result.getIsSuccess() == 1) {
            String paymentSetting = (String) ((Map) result.getData()).get("paymentSetting");
            if (!Strings.isNullOrEmpty(paymentSetting) && !paymentSetting.startsWith("{")) {
                return false;
            }
            JSONObject jsonObject = JSONObject.fromObject(paymentSetting);
            //{offline:0,online:0}
            if (jsonObject != null && jsonObject.containsKey("offline")) {
                return "1".equalsIgnoreCase(jsonObject.getString("offline"));
            }
        }
        return false;
    }

    private Boolean getDrawCash(JSONObject jsonObject) {
        if (jsonObject != null && jsonObject.containsKey("isOpenPointWithdraw")) {
            return "1".equalsIgnoreCase(jsonObject.getString("isOpenPointWithdraw"));
        }
        return false;
    }

    private Boolean getDrawGold(JSONObject jsonObject) {
        if (jsonObject != null && jsonObject.containsKey("isOpenPointWithdrawEntity")) {
            return "1".equalsIgnoreCase(jsonObject.getString("isOpenPointWithdrawEntity"));
        }
        return false;
    }

    public JSONObject getBizConfig(Long companyID) {
        DataResult result = HttpUtil.httpGet(ProConstants.getBizConfig + companyID, restTemplate);
        if (result.getIsSuccess() == 1) {
            return JSONObject.fromObject(result.getData());
        }
        return null;
    }

    private Boolean getOfflinePermission(Long userID) {
        DataResult result = HttpUtil.httpGet(
                ProConstants.getOfflinePermission + userID, restTemplate);
        if (!(result.getIsSuccess() == 1)) {
            throw new ServiceException("用户权限获取失败!", RestConst.ErrorCode.SERVICE_FAIL);
        }

        List<String> list = (List<String>) result.getData();
        for (String per : list) {
            if (per.equals("check")) {
                return true;
            }
        }
        return false;
    }


    /**
     * 下属部门或用户订单统计
     *
     * @param orderByDto orderByField排序字段 orderQty则按订单数量，transactionTotal则按交易额
     * @param pageNum
     * @param pageSize
     * @return
     */
    public Object selectCountByDepartment(UserIDOrderByDto orderByDto, int pageNum, int pageSize) {
        UserForOrderCountDto userForOrderCountDto = (UserForOrderCountDto) getUserAndCount(orderByDto.getUserID(), 1);

        List<OrderCountMoreVo> moreVoList = new ArrayList<>();
        Map<String, Object> param = new HashMap<>();
        param.put("orderByField", orderByDto.getOrderByField());
        PageHelper.startPage(pageNum, pageSize);

        int type = 0;  //用于调用base查询会员信息
        if (userForOrderCountDto.getType() == 2) {  //销售经理统计下属销售顾问订单数据
            type = 5;
            param.put("salesManagerID", orderByDto.getUserID());
            moreVoList = orderInfoMapper.selectCountByManagerID(param);
        }
        if (userForOrderCountDto.getType() == 1) { //管理员统计下属组织部门数据
            switch (userForOrderCountDto.getLevel()) {
                case 1:
                    type = 1;
                    param.put("companyID", SystemContext.getCompanyID());
                    moreVoList = countOrderMapper.selectGroupByBranchID(param);
                    break;
                case 2:
                    type = 2;
                    param.put("branchID", userForOrderCountDto.getOrganizationalID());
                    param.put("companyID", SystemContext.getCompanyID());
                    moreVoList = countOrderMapper.selectGroupByTwoLevelBranchID(param);
                    break;
                case 3:
                    type = 3;
                    param.put("twoLevelBranchID", userForOrderCountDto.getOrganizationalID());
                    param.put("companyID", SystemContext.getCompanyID());
                    moreVoList = countOrderMapper.selectGroupBySubbranchID(param);
                    break;
                case 4:
                    type = 4;
                    param.put("subbranchID", userForOrderCountDto.getOrganizationalID());
                    param.put("companyID", SystemContext.getCompanyID());
                    moreVoList = countOrderMapper.selectGroupBySalesManagerID(param);
                    break;
            }
        }

        if (moreVoList.size() > 0) {
            List<Long> ozOrUserIDList = new ArrayList<>();  //用于调用base服务查询name，顾问、会员数
            for (OrderCountMoreVo moreVo : moreVoList) {
                ozOrUserIDList.add(moreVo.getoOrUserID());
            }
            List<UserOnlyQtyVo> onlyQtyVoList = getUserQtyFromBase(ozOrUserIDList, type);

            for (OrderCountMoreVo moreVo : moreVoList) {
                Long oOrUserID = moreVo.getoOrUserID();
                for (UserOnlyQtyVo onlyQtyVo : onlyQtyVoList) {
                    if (onlyQtyVo.getoOrUserID().equals(oOrUserID)) {
                        moreVo.setoOrUserName(onlyQtyVo.getoOrUserName());
                        moreVo.setMemberCount(onlyQtyVo.getMemberCount());
                        moreVo.setSalesCount(onlyQtyVo.getSalesCount());
                        moreVo.setUserQty(onlyQtyVo.getUserQty());
                    }
                }
            }
        }
        PageInfo<OrderCountMoreVo> page = new PageInfo(moreVoList);
        return page;
    }

    /**
     * 分类/交易金额统计趋势
     *
     * @param orderCountDto
     * @param type          0 startTime，endTime自选，1最近七天，2最近一月，3最近三月
     * @return
     */
    public Object getTransactionClassifyCountTred(OrderCountDto orderCountDto, int type) {
        Long startTime;
        Long endTime;
        switch (type) {
            case 0:
                if (orderCountDto.getStartTime() == null || orderCountDto.getEndTime() == null) {
                    throw new ServiceException("请传入时间戳", RestConst.ErrorCode.FORM_FAIL);
                }
                startTime = orderCountDto.getStartTime();
                endTime = orderCountDto.getEndTime();
                break;
            case 1:
                startTime = getTimesamp(4);
                endTime = getTimesamp(2) - 1;
                break;
            case 2:
                startTime = getTimesamp(5);
                endTime = getTimesamp(2) - 1;
                break;
            case 3:
                startTime = getTimesamp(6);
                endTime = getTimesamp(2) - 1;
                break;
            default:
                throw new ServiceException("type参数传入错误", RestConst.ErrorCode.FORM_FAIL);
        }
        Map<String, Object> resultMap = new HashMap<>();
        orderCountDto.setStartTime(startTime);
        orderCountDto.setEndTime(endTime);
        resultMap.put("classifySalesTred", getClassifyCountTred(orderCountDto));

        orderCountDto.setStartTime(startTime);
        orderCountDto.setEndTime(endTime);
        resultMap.put("orderTransactionTred", getTransactionTrend(orderCountDto));
        return resultMap;
    }

    //商品销量统计
    public Object getGoodsSales(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Map<String, Object> param = new HashMap<>();
        param.put("orderBy", "salesTotal");
        param.put("companyID", SystemContext.getCompanyID());
        List<Map<String, Object>> goodsMapList = orderItemMapper.selectGoodsSalesMore(param);
        for (Map<String, Object> map : goodsMapList) {
            if (map.get("salesTotal") == null) {
                map.put("salesTotal", 0);
            }
        }
        PageInfo<Map<String, Object>> page = new PageInfo(goodsMapList);
        return page;
    }

    /**
     * 根据List<oIDOrUserID>,type 来查询对应的销售额，会员统计需求
     *
     * @param oOrUserIDList
     * @param type          1分行ID，2二级分行ID，3支行ID，4销售经理ID，5销售顾问ID
     * @return
     */
    public Object getTransactionByList(List<Long> oOrUserIDList, int type) {
        List<OrderCountMoreVo> moreVOList = new ArrayList<>();
        Map<String, Object> param = new HashMap<>();
        switch (type) {
            case 1:
                OrderCountMoreVo orderCountMoreVo = new OrderCountMoreVo();
                //CountOrder countOrder = countOrderMapper.selectByPrimaryKey(1l);
                CountOrder countOrder = countOrderMapper.selectByPrimaryKey(Longs.tryParse(SystemContext.getCompanyID().toString().substring(0, SystemContext.getCompanyID().toString().length() - 1)));
                orderCountMoreVo.setoOrUserID(1l);
                orderCountMoreVo.setoOrUserName("总部");
                orderCountMoreVo.setOrderQty(countOrder.getOrderCount());
                orderCountMoreVo.setTransactionTotal(countOrder.getTotalAmount());
                param.put("branchIDList", oOrUserIDList);
                param.put("companyID", SystemContext.getCompanyID());
                moreVOList = countOrderMapper.selectGroupByBranchID(param);
                moreVOList.add(orderCountMoreVo);
                break;
            case 2:
                param.put("twoLevelBranchIDList", oOrUserIDList);
                param.put("companyID", SystemContext.getCompanyID());
                moreVOList = countOrderMapper.selectGroupByTwoLevelBranchID(param);
                break;
            case 3:
                param.put("subbranchIDList", oOrUserIDList);
                param.put("companyID", SystemContext.getCompanyID());
                moreVOList = countOrderMapper.selectGroupBySubbranchID(param);
                break;
            case 4:
                param.put("salesManagerIDList", oOrUserIDList);
                param.put("companyID", SystemContext.getCompanyID());
                moreVOList = countOrderMapper.selectGroupBySalesManagerID(param);
                break;
            case 5:
                moreVOList = orderInfoMapper.selectByPaterIDList(oOrUserIDList);
                break;
        }
        Map<String, Object> resultMap = new HashMap<>();
        if (moreVOList.size() > 0) {
            for (OrderCountMoreVo moreVo : moreVOList) {
                resultMap.put(moreVo.getoOrUserID().toString(), moreVo.getTransactionTotal());
            }
        }
        return resultMap;
    }

    //查询交易额趋势，查询主表,开始、结束时间必传
    public Map<Long, BigDecimal> getTransactionTrend(OrderCountDto countDto) {
        if (countDto.getStartTime() == null || countDto.getEndTime() == null) {
            throw new ServiceException("时间参数不能为空", RestConst.ErrorCode.SERVICE_FAIL);
        }
        Map<Integer, Long> params = getTimesampInterval(countDto.getStartTime(), countDto.getEndTime());

        Map<Long, BigDecimal> trendParam = new LinkedHashMap<>();
        for (int i = 1; i < 8; i++) {
            countDto.setStartTime(params.get(i));
            countDto.setEndTime(params.get(i + 1));
            BigDecimal transactionTotal = getTransactionByInfo(countDto);
            trendParam.put(params.get(i + 1), transactionTotal);
        }
        return trendParam;
    }

    //add首页时间查询当天
    //查询交易额趋势，查询主表,开始、结束时间必传
    public Map<Long, BigDecimal> getTransactionTrend1(OrderCountDto countDto) {
        if (countDto.getStartTime() == null || countDto.getEndTime() == null) {
            throw new ServiceException("时间参数不能为空", RestConst.ErrorCode.SERVICE_FAIL);
        }
        Map<Integer, Long> params = getTimesampInterval(countDto.getStartTime(), countDto.getEndTime());

        Map<Long, BigDecimal> trendParam = new LinkedHashMap<>();
        for (int i = 1; i < 8; i++) {
            countDto.setStartTime(params.get(i));
            countDto.setEndTime(params.get(i + 1));
            BigDecimal transactionTotal = getTransactionByInfo1(countDto);
            trendParam.put(params.get(i + 1), transactionTotal);
        }
        return trendParam;
    }


    //查询按商品分类统计商品销量趋势，查询order_item表，开始，结束时间必传
    public Object getClassifyCountTred(OrderCountDto orderCountDto) {
        if (orderCountDto.getStartTime() == null || orderCountDto.getEndTime() == null) {
            throw new ServiceException("时间参数不能为空", RestConst.ErrorCode.SERVICE_FAIL);
        }
        Map<Integer, Long> params = getTimesampInterval(orderCountDto.getStartTime(), orderCountDto.getEndTime());  //八个时间点

        Map<String, List<ClassifyCountTredVo>> classifyParam = new HashMap<>();
        Map<String, Integer> classifyTotal = new LinkedHashMap<>();  //用于排序取前五条

        for (int i = 1; i < 8; i++) {
            orderCountDto.setStartTime(params.get(i));
            orderCountDto.setEndTime(params.get(i + 1));
            List<ClassifyCountVo> countVoList = getClassifyCount(orderCountDto);
            for (ClassifyCountVo countVo : countVoList) {
                ClassifyCountTredVo classifyCountTredVo = new ClassifyCountTredVo();
                classifyCountTredVo.setTimesamp(params.get(i + 1));
                classifyCountTredVo.setQty(countVo.getCountQty());
                List<ClassifyCountTredVo> tredVoList = new ArrayList<>();
                if (classifyParam.get(countVo.getClassifyName()) == null) {
                    tredVoList.add(classifyCountTredVo);
                } else {
                    tredVoList = classifyParam.get(countVo.getClassifyName());
                    tredVoList.add(classifyCountTredVo);
                }
                classifyParam.put(countVo.getClassifyName(), tredVoList);
                int qty = classifyTotal.get(countVo.getClassifyName()) == null ? countVo.getCountQty() : classifyTotal.get(countVo.getClassifyName()) + countVo.getCountQty();
                classifyTotal.put(countVo.getClassifyName(), qty);
            }
        }
        classifyTotal = sortMap(classifyTotal); //排序
        Map<String, List<ClassifyCountTredVo>> resultMap = new LinkedHashMap<>();
        for (String key : classifyTotal.keySet()) {
            resultMap.put(key, classifyParam.get(key));
        }
        return resultMap;
    }

    //查询银行待扣点金额，已扣点金额
    public Object getTotalCommission(Long branchID) {
        BigDecimal commission = orderService.selectCommission(branchID); //已结算扣点金额
        BigDecimal totalCommission = orderService.selectTotalCommission(branchID); //扣点总金额
        BigDecimal totalEmployeeCommission = orderService.selectTotalEmployeeCommission(branchID); //扣点总金额
        commission = (commission == null ? BigDecimal.ZERO : commission);
        totalCommission = (totalCommission == null ? BigDecimal.ZERO : totalCommission);
        totalEmployeeCommission = (totalEmployeeCommission == null ? BigDecimal.ZERO : totalEmployeeCommission);
        Map<String, Object> param = new HashMap<>();
        param.put("totalCommission", totalCommission);
        param.put("totalEmployeeCommission", totalEmployeeCommission);
        param.put("commission", commission);
        param.put("notCommission", totalCommission.subtract(commission)); //未结算扣点金额
        return param;
    }

    //仅仅查询本部统计数据
    public Object getSelfInfo(Long userID) {
        UserForOrderCountDto userForOrderCountDto = (UserForOrderCountDto) getUserAndCount(userID, 1);
        OrderCountMoreVo orderCountMoreVo = new OrderCountMoreVo();
        int type = 1;
        if (userForOrderCountDto.getLevel() == 1) {
            //CountOrder countOrder = countOrderMapper.selectByPrimaryKey(1l);
            CountOrder countOrder = countOrderMapper.selectByPrimaryKey(Longs.tryParse(SystemContext.getCompanyID().toString().substring(0, SystemContext.getCompanyID().toString().length() - 1)));
            orderCountMoreVo.setoOrUserID(1l);
            orderCountMoreVo.setoOrUserName("总部");
            orderCountMoreVo.setOrderQty(countOrder.getOrderCount());
            orderCountMoreVo.setTransactionTotal(countOrder.getTotalAmount());
        } else {
            OrderCountDto orderCountDto = new OrderCountDto();
            switch (userForOrderCountDto.getLevel()) {
                case 2:
                    orderCountDto.setBranchID(userForOrderCountDto.getOrganizationalID());
                    orderCountDto.setTwoLevelBranchID(0l);
                    orderCountDto.setSubbranchID(0l);
                    orderCountDto.setSalesManagerID(0l);
                    break;
                case 3:
                    type = 2;
                    orderCountDto.setTwoLevelBranchID(userForOrderCountDto.getOrganizationalID());
                    orderCountDto.setSubbranchID(0l);
                    orderCountDto.setSalesManagerID(0l);
                    break;
                case 4:
                    type = 3;
                    orderCountDto.setSubbranchID(userForOrderCountDto.getOrganizationalID());
                    orderCountDto.setSalesManagerID(0l);
                    break;
            }
            orderCountDto.setCompanyID(SystemContext.getCompanyID());
            OrderCountVo orderCountVo = countOrderMapper.selectByCondition(orderCountDto);
            orderCountMoreVo.setoOrUserID(userForOrderCountDto.getOrganizationalID());
            orderCountMoreVo.setOrderQty(orderCountVo.getOrderQty());
            orderCountMoreVo.setTransactionTotal(orderCountVo.getTransactionTotal());
        }
        List<Long> oIDList = new ArrayList<>();
        oIDList.add(userForOrderCountDto.getOrganizationalID());
        List<UserOnlyQtyVo> onlyQtyVoList = getUserQtyFromBase(oIDList, type);
        for (UserOnlyQtyVo onlyQtyVo : onlyQtyVoList) {
            if (onlyQtyVo.getoOrUserID().equals(orderCountMoreVo.getoOrUserID())) {
                orderCountMoreVo.setoOrUserName(onlyQtyVo.getoOrUserName());
                orderCountMoreVo.setMemberCount(onlyQtyVo.getMemberCount());
                orderCountMoreVo.setSalesCount(onlyQtyVo.getSalesCount());
                orderCountMoreVo.setUserQty(onlyQtyVo.getUserQty());
            }
        }
        return orderCountMoreVo;
    }

    /**
     * -----------------------------------银行对账单-------------------------------------
     */

    //查询部门待核对、已核对数据
    public Object getSettleTotal(String oID, Long supplierID) {
        Map<String, Object> param = getNameLevelByOID(oID);
        int level = Integer.valueOf(param.get("level").toString());
        BankSettleSelectDto selectDto = new BankSettleSelectDto();//查询条件
        switch (level) {
            case 1:
                break;
            case 2:
                selectDto.setBranchID(oID);
                break;
            case 3:
                selectDto.setTwoLevelBranchID(oID);
                break;
            case 4:
                selectDto.setSubbranchID(oID);
                break;
        }
        Map<String, BigDecimal> resultMap = new HashMap<>();
        selectDto.setCompanyID(SystemContext.getCompanyID());
        selectDto.setSupplierID(supplierID);
        Object object = orderBankSettlementMapper.selectSettleTotal(selectDto);
        if (object != null) {
            resultMap = (Map<String, BigDecimal>) object;
        }
        if (resultMap.get("settle") == null) {
            resultMap.put("settle", BigDecimal.ZERO);
        }
        if (resultMap.get("notSettle") == null) {
            resultMap.put("notSettle", BigDecimal.ZERO);
        }
        return resultMap;
    }

    //根据分行or总行ID来查询有待核对数据的月份数据
    public Object getSettleData(String oID, Long supplierID) {
        Map<String, Object> param = getNameLevelByOID(oID);
        int level = Integer.valueOf(param.get("level").toString());
        BankSettleSelectDto bankSettleSelectDto = new BankSettleSelectDto();
        switch (level) {
            case 1:
                bankSettleSelectDto.setTwoLevelBranchID("0");
                break;
            case 2:
                bankSettleSelectDto.setBranchID(oID);
                break;
            case 3:
                bankSettleSelectDto.setTwoLevelBranchID(oID);
                break;
            case 4:
                bankSettleSelectDto.setSubbranchID(oID);
                break;
        }
        bankSettleSelectDto.setSupplierID(supplierID);
        bankSettleSelectDto.setCompanyID(SystemContext.getCompanyID());
        List<Map<String, Integer>> mapList = orderBankSettlementMapper.selectNotSettleYM(bankSettleSelectDto);

        List<BankSettleAllDataVo> allDataVoList = new ArrayList<>(); //结果集合
        if (mapList.size() > 0) {
            for (Map<String, Integer> map : mapList) {
                BankSettleAllDataVo allDataVo = new BankSettleAllDataVo(); //结果
                allDataVo.setYear(map.get("year"));
                allDataVo.setMonth(map.get("month"));
                BankSettleDto settleDto = new BankSettleDto();  //查询条件
                settleDto.setoID(oID);
                settleDto.setYear(map.get("year").toString());
                settleDto.setMonth(map.get("month").toString());
                settleDto.setSupplierID(bankSettleSelectDto.getSupplierID());
                Map<String, BigDecimal> resultMap = (Map<String, BigDecimal>) getBankSettleTotal(settleDto, 1, 1);
                allDataVo.setTotalCommission(resultMap.get("totalCommission"));
                allDataVo.setTotalTransactions(resultMap.get("totalTransactions"));
                allDataVo.setTotalSettle(resultMap.get("totalSettle"));

                List<BankSettleSelectVo> selectVoList = (List<BankSettleSelectVo>) getBankSettlementListp(settleDto);
                allDataVo.setBankSettleSelectVoList(selectVoList);
                allDataVoList.add(allDataVo);
            }
        }
        return allDataVoList;
    }


    /**
     * 根据部门ID查询未核对对账单按供应商分 查询部门以及子部门
     *
     * @param oID
     * @param year
     * @param month
     * @return
     */
    public Object getBankSettleListGroupSeller(Long oID, int year, int month) {
        Map<String, Object> param = getNameLevelByOID(String.valueOf(oID));
        int level = Integer.valueOf(param.get("level").toString());
        BankSettleSellerSelectDto settleSelectDto = new BankSettleSellerSelectDto();
        settleSelectDto.setCompanyID(SystemContext.getCompanyID());
        settleSelectDto.setYear(year);
        settleSelectDto.setMonth(month);
        switch (level) {
            case 1:
                settleSelectDto.setBranchID(0L);
                break;
            case 2:
                settleSelectDto.setBranchID(oID);
                break;
            case 3:
                settleSelectDto.setTwoLevelBranchID(oID);
                break;
            case 4:
                settleSelectDto.setSubbranchID(oID);
                break;
        }
        return orderBankSettlementMapper.getSellerGroupList(settleSelectDto);
    }

    /**
     * 根据部门ID查询未核对对账单按供应商分 只查询本部分
     *
     * @param oID
     * @param year
     * @param month
     * @return
     */
    public Object getBankSettleSellerListSelf(Long oID, int year, int month) {
        Map<String, Object> param = getNameLevelByOID(String.valueOf(oID));
        int level = Integer.valueOf(param.get("level").toString());
        BankSettleSellerSelectDto settleSelectDto = new BankSettleSellerSelectDto();
        settleSelectDto.setCompanyID(SystemContext.getCompanyID());
        settleSelectDto.setYear(year);
        settleSelectDto.setMonth(month);
        switch (level) {
            case 1:
                settleSelectDto.setBranchID(0L);
                break;
            case 2:
                settleSelectDto.setBranchID(oID);
                settleSelectDto.setTwoLevelBranchID(0L);

                break;
            case 3:
                settleSelectDto.setTwoLevelBranchID(oID);
                settleSelectDto.setSubbranchID(0L);
                break;
            case 4:
                settleSelectDto.setSubbranchID(oID);
                break;
        }
        return orderBankSettlementMapper.getSellerGroupList(settleSelectDto);
    }


    //根据分行or总行ID、年、月来核对确认(总行的OID传0)
    public Object getBankSettle(BankSettleDto bankSettleDto) {
        bankSettleDto.setUpdateTime(CommonUtils.getCurTimestamp());
        return orderBankSettlementMapper.updateSettle(bankSettleDto);
    }

    /**
     * 根据银行ID、年、月查询银行交易额、中收额
     *
     * @param bankSettleDto
     * @param type          1不限制 2包含未核对数据则不显示
     * @param selfType      1查询本部及其下属所有 2仅查询本部
     * @return
     */
    public Object getBankSettleTotal(BankSettleDto bankSettleDto, int type, int selfType) {
        Map<String, Object> param = getNameLevelByOID(bankSettleDto.getoID());
        int level = Integer.valueOf(param.get("level").toString());
        BankSettleSelectDto selectDto = new BankSettleSelectDto();//查询该部门及其下属部门数据条件
        BankSettleSelectDto selectDto1 = new BankSettleSelectDto();  //仅查询该部门本身的数据
        selectDto.setYear(bankSettleDto.getYear());
        selectDto.setMonth(bankSettleDto.getMonth());
        selectDto.setSupplierID(bankSettleDto.getSupplierID());

        selectDto1.setYear(bankSettleDto.getYear());
        selectDto1.setMonth(bankSettleDto.getMonth());
        selectDto1.setSupplierID(bankSettleDto.getSupplierID());

        BankSettleSelectDto settleSelectDto = new BankSettleSelectDto();//查询有待核对数据的月份
        switch (level) {
            case 1:
                selectDto1.setBranchID("0");
                break;
            case 2:
                selectDto1.setBranchID(bankSettleDto.getoID());
                selectDto1.setTwoLevelBranchID("0");

                settleSelectDto.setBranchID(bankSettleDto.getoID());
                selectDto.setBranchID(bankSettleDto.getoID());
                break;
            case 3:
                selectDto1.setTwoLevelBranchID(bankSettleDto.getoID());
                selectDto1.setSubbranchID("0");

                settleSelectDto.setTwoLevelBranchID(bankSettleDto.getoID());
                selectDto.setTwoLevelBranchID(bankSettleDto.getoID());
                break;
            case 4:
                selectDto1.setSubbranchID(bankSettleDto.getoID());

                settleSelectDto.setSubbranchID(bankSettleDto.getoID());
                selectDto.setSubbranchID(bankSettleDto.getoID());
                break;
        }

        if (type == 2) {
            //如果包含未核对数据则不显示
            settleSelectDto.setYear(bankSettleDto.getYear());
            settleSelectDto.setMonth(bankSettleDto.getMonth());
            settleSelectDto.setCompanyID(SystemContext.getCompanyID());
            settleSelectDto.setSupplierID(bankSettleDto.getSupplierID());
            List<Map<String, Integer>> mapList = orderBankSettlementMapper.selectNotSettleYM(settleSelectDto);
            if (mapList.size() > 0) {
                Map<String, Integer> mapfor = new HashMap<>();
                mapfor.put("year", Integer.valueOf(bankSettleDto.getYear()));
                mapfor.put("month", Integer.valueOf(bankSettleDto.getMonth()));
                if (mapList.contains(mapfor)) {
                    return null;
                }
            }
        }

        Map<String, BigDecimal> resultMap = new HashMap<>();
        Object object = new Object();
        switch (selfType) {
            case 1:
                selectDto.setCompanyID(SystemContext.getCompanyID());
                object = orderBankSettlementMapper.selectByConditon(selectDto);
                break;
            case 2:
                selectDto1.setCompanyID(SystemContext.getCompanyID());
                object = orderBankSettlementMapper.selectByConditon(selectDto1);
                break;
        }

        if (object != null) {
            resultMap = (Map<String, BigDecimal>) object;
        }
        if (resultMap.get("totalTransactions") == null) {
            resultMap.put("totalTransactions", BigDecimal.ZERO);
        }
        if (resultMap.get("totalCommission") == null) {
            resultMap.put("totalCommission", BigDecimal.ZERO);
        }
        resultMap.put("totalSettle", resultMap.get("totalTransactions").subtract(resultMap.get("totalCommission")));
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("oName", param.get("oName"));
        returnMap.put("totalTransactions", resultMap.get("totalTransactions"));
        returnMap.put("totalCommission", resultMap.get("totalCommission"));
        returnMap.put("totalSettle", resultMap.get("totalSettle"));
        return returnMap;
    }

    /**
     * 根据银行ID、年、月查询银行本部及其下级部门对账单
     *
     * @param bankSettleDto
     * @param type          1不限制 2包含未核对数据则不显示
     * @return
     */
    public Object getBankSettlementList(BankSettleDto bankSettleDto, int type, int pageNum, int pageSize) {
        Map<String, Object> param = getNameLevelByOID(bankSettleDto.getoID());
        int level = Integer.valueOf(param.get("level").toString());

        List<BankSettleSelectVo> selectVoList = new ArrayList<>();//结果
        BankSettleSelectDto selectDto = new BankSettleSelectDto();//查询条件
        selectDto.setYear(bankSettleDto.getYear());
        selectDto.setMonth(bankSettleDto.getMonth());
        selectDto.setSupplierID(bankSettleDto.getSupplierID());

        BankSettleSelectDto settleSelectDto = new BankSettleSelectDto();//查询包含待核对数据的月份
        PageHelper.startPage(pageNum, pageSize);
        switch (level) {
            case 1:
                selectDto.setCompanyID(SystemContext.getCompanyID());
                selectVoList = orderBankSettlementMapper.selectBranchList(selectDto);
                break;
            case 2:
                settleSelectDto.setBranchID(bankSettleDto.getoID());

                selectDto.setBranchID(bankSettleDto.getoID());
                selectDto.setCompanyID(SystemContext.getCompanyID());
                selectVoList = orderBankSettlementMapper.selectTwoLevelList(selectDto);
                break;
            case 3:
                settleSelectDto.setTwoLevelBranchID(bankSettleDto.getoID());

                selectDto.setTwoLevelBranchID(bankSettleDto.getoID());
                selectDto.setCompanyID(SystemContext.getCompanyID());
                selectVoList = orderBankSettlementMapper.selectSubList(selectDto);
                break;
            case 4:
                settleSelectDto.setSubbranchID(bankSettleDto.getoID());

                selectDto.setSubbranchID(bankSettleDto.getoID());
                selectDto.setCompanyID(SystemContext.getCompanyID());
                selectVoList = orderBankSettlementMapper.selectSelfDept(selectDto);
                break;
        }

        if (type == 2) {
            //如果包含未核对数据则不显示
            settleSelectDto.setYear(bankSettleDto.getYear());
            settleSelectDto.setMonth(bankSettleDto.getMonth());
            settleSelectDto.setSupplierID(bankSettleDto.getSupplierID());
            settleSelectDto.setCompanyID(SystemContext.getCompanyID());
            List<Map<String, Integer>> mapList = orderBankSettlementMapper.selectNotSettleYM(settleSelectDto);
            if (mapList.size() > 0) {
                Map<String, Integer> mapfor = new HashMap<>();
                mapfor.put("year", Integer.valueOf(bankSettleDto.getYear()));
                mapfor.put("month", Integer.valueOf(bankSettleDto.getMonth()));
                if (mapList.contains(mapfor)) {
                    return null;
                }
            }
        }

        List<Long> oIDList = new ArrayList<>();
        if (selectVoList.size() > 0) {
            for (BankSettleSelectVo selectVo : selectVoList) {
                oIDList.add(selectVo.getoID());
            }
        }

        if (oIDList.size() > 0) {
            //获取部门名称
            Map<String, Object> nameMap = getBranchMap(oIDList);
            for (BankSettleSelectVo selectVo : selectVoList) {
                selectVo.setLevel(level + 1);
                if (selectVo.getoID() == 0) {
                    selectVo.setoID(Long.parseLong(bankSettleDto.getoID()));
                    selectVo.setoName(param.get("oName").toString() + "本部");
                } else {
                    String oName = nameMap.get(selectVo.getoID().toString()).toString();
                    selectVo.setoName(oName);
                }
            }
        }

        PageInfo<BankSettleSelectVo> page = new PageInfo(selectVoList);
        return page;
    }

    //根据银行ID、年、月查询银行本部及其下级部门对账单（不分页，不做查询限制）
    private Object getBankSettlementListp(BankSettleDto bankSettleDto) {
        Map<String, Object> param = getNameLevelByOID(bankSettleDto.getoID());
        int level = Integer.valueOf(param.get("level").toString());
        List<BankSettleSelectVo> selectVoList = new ArrayList<>();//结果
        BankSettleSelectDto selectDto = new BankSettleSelectDto();//查询条件
        selectDto.setYear(bankSettleDto.getYear());
        selectDto.setMonth(bankSettleDto.getMonth());
        selectDto.setSupplierID(bankSettleDto.getSupplierID());

        switch (level) {
            case 1:
                selectDto.setCompanyID(SystemContext.getCompanyID());
                selectVoList = orderBankSettlementMapper.selectBranchList(selectDto);
                break;
            case 2:
                selectDto.setBranchID(bankSettleDto.getoID());
                selectDto.setCompanyID(SystemContext.getCompanyID());
                selectVoList = orderBankSettlementMapper.selectTwoLevelList(selectDto);
                break;
            case 3:
                selectDto.setTwoLevelBranchID(bankSettleDto.getoID());
                selectDto.setCompanyID(SystemContext.getCompanyID());
                selectVoList = orderBankSettlementMapper.selectSubList(selectDto);
                break;
            case 4:
                selectDto.setSubbranchID(bankSettleDto.getoID());
                selectDto.setCompanyID(SystemContext.getCompanyID());
                selectVoList = orderBankSettlementMapper.selectSelfDept(selectDto);
                break;
        }

        List<Long> oIDList = new ArrayList<>();
        if (selectVoList.size() > 0) {
            for (BankSettleSelectVo selectVo : selectVoList) {
                oIDList.add(selectVo.getoID());
            }
        }

        if (oIDList.size() > 0) {
            //获取部门名称
            Map<String, Object> nameMap = getBranchMap(oIDList);
            for (BankSettleSelectVo selectVo : selectVoList) {
                selectVo.setLevel(level + 1);
                if (selectVo.getoID() == 0) {
                    selectVo.setoID(Long.parseLong(bankSettleDto.getoID()));
                    selectVo.setoName(param.get("oName").toString() + "本部");
                } else {
                    String oName = nameMap.get(selectVo.getoID().toString()).toString();
                    selectVo.setoName(oName);
                }
            }
        }
        return selectVoList;
    }

    //获取银行的名称和级别
    private Map<String, Object> getNameLevelByOID(String oID) {
        DataResult result = HttpUtil.httpGet(ProConstants.getNameLevelByOID + oID, restTemplate);
        if (result.getIsSuccess() == 0) {
            throw new ServiceException("调用base服务获取银行信息失败", RestConst.ErrorCode.SERVICE_FAIL);
        }
        return (Map<String, Object>) result.getData();
    }

    //获取oID对应的name的List
    private Map<String, Object> getBranchMap(List<Long> list) {
        DataResult result = HttpUtil.httpPost(ProConstants.getBranchList, list, restTemplate);
        if (result.getIsSuccess() != 1) {
            throw new ServiceException("调用base服务查询银行信息失败", RestConst.ErrorCode.SERVICE_FAIL);
        }
        return (Map<String, Object>) result.getData();
    }


    /**-----------------------------------银行对账单-------------------------------------*/

    /**
     * 获取对应IDList的name,顾问、会员数量，调用base服务
     *
     * @param ozOrUserIDList
     * @param type           1分行ID，2二级分行ID，3支行ID，4销售经理ID，5销售顾问ID
     * @return
     */
    private List<UserOnlyQtyVo> getUserQtyFromBase(List<Long> ozOrUserIDList, int type) {
        List<UserOnlyQtyVo> onlyQtyVoList = new ArrayList<>();
        DataResult result = HttpUtil.httpPost(ProConstants.getUserQtyByList + type, ozOrUserIDList, restTemplate);
        if (result.getIsSuccess() == 1) {
            JSONArray jsonArray = JSONArray.fromObject(result.getData());
            onlyQtyVoList = (List) jsonArray.toCollection(jsonArray, UserOnlyQtyVo.class);
        } else {
            System.out.print("调用base服务获取对应IDList的name,顾问、会员数量失败");
        }
        return onlyQtyVoList;
    }

    //按id查询统计数据
    private CountOrder getCountByID(Long id) {
        CountOrder countOrder = new CountOrder();
        Object object = countOrderMapper.selectByPrimaryKey(id);
        if (object == null) {
            countOrder.setOrderCount(0);
            countOrder.setTotalAmount(BigDecimal.ZERO);
        } else {
            countOrder = (CountOrder) object;
        }
        return countOrder;
    }

    //按条件获取交易额和订单数【查询统计表】
    private OrderCountVo getOrderCountByCondition(OrderCountDto orderCountDto) {
        OrderCountVo orderCountVo = new OrderCountVo();
        orderCountDto.setCompanyID(SystemContext.getCompanyID());
        Object object = countOrderMapper.selectByCondition(orderCountDto);
        if (object == null) {
            orderCountVo.setOrderQty(0);
            orderCountVo.setTransactionTotal(BigDecimal.ZERO);
        } else {
            orderCountVo = (OrderCountVo) object;
        }
        return orderCountVo;
    }

    //按条件获取交易额总额【查询主表order_info】
    private BigDecimal getTransactionByInfo(OrderCountDto orderCountDto) {
        orderCountDto.setCompanyID(SystemContext.getCompanyID());
        OrderCountVo orderCountVo = orderInfoMapper.selectOrderCount(orderCountDto);
        if (orderCountVo.getTransactionTotal() == null) {
            orderCountVo.setTransactionTotal(BigDecimal.ZERO);
        }
        return orderCountVo.getTransactionTotal();
    }

    //按条件获取交易额总额【查询主表order_info】当天
    private BigDecimal getTransactionByInfo1(OrderCountDto orderCountDto) {
        orderCountDto.setCompanyID(SystemContext.getCompanyID());
        OrderCountVo orderCountVo = orderInfoMapper.selectOrderAmountCount(orderCountDto);
        if (orderCountVo.getTransactionTotal() == null) {
            orderCountVo.setTransactionTotal(BigDecimal.ZERO);
        }
        return orderCountVo.getTransactionTotal();
    }


    //查询按商品分类的销量趋势,查询order_item表
    private List<ClassifyCountVo> getClassifyCount(OrderCountDto orderCountDto) {
        JSONObject jsonObject = rest.getForObject(classifyUrl + CommonTools.getExtString(rest, "classifyType"), JSONObject.class);
        if (jsonObject.getInt("isSuccess") != 1) {
            throw new ServiceException("调用云管控服务出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        List<JSONObject> objectList = jsonObject.getJSONArray("data");
        orderCountDto.setCompanyID(SystemContext.getCompanyID());
        List<ClassifyCountVo> classifyList = orderItemMapper.selectCountByClassify(orderCountDto);

        //已经产生数据的分类ID集合，用于判断
        List<String> classifyIDList = new ArrayList<>();
        if (classifyList.size() > 0) {
            for (ClassifyCountVo classifyCountVo : classifyList) {
                classifyCountVo.setCountQty(classifyCountVo.getCountQty() == null ? 0 : classifyCountVo.getCountQty());
                classifyIDList.add(classifyCountVo.getClassifyID());
            }
        }

        //未产生数据的分类则销量为0
        for (JSONObject jsonObject1 : objectList) {
            if (!classifyIDList.contains(jsonObject1.get("clazzid").toString())) {
                ClassifyCountVo classifyCountVo = new ClassifyCountVo();
                classifyCountVo.setClassifyID(jsonObject1.get("clazzid").toString());
                classifyCountVo.setClassifyName(jsonObject1.get("clazzname").toString());
                classifyCountVo.setCountQty(0);
                classifyList.add(classifyCountVo);
            }
        }
        return classifyList;
    }

    //获取内部员工用户信息及其统计信息[1仅获取用户信息，2并且获取用户统计信息]
    private Object getUserAndCount(Long userID, int type) {
        try {
            JSONObject jsonObject = HttpUtil.httpGetJSONObject(ProConstants.getUserForOrderCount + userID + "/" + type, restTemplate);
            return JSONObject.toBean(jsonObject.getJSONObject("data"), UserAndCountDto.class);
        } catch (Exception e) {
            throw new ServiceException("调用base服务失败", e);
        }
    }

    //获取内部员工用户统计信息
    private JSONObject selectUserStatCount(Long userID, Long selectUserStatCount) {
        try {
            JSONObject jsonObject = HttpUtil.httpGetJSONObject(ProConstants.getUserInfoStatCount + userID + "/" + selectUserStatCount, restTemplate);
            return jsonObject.getJSONObject("data");
        } catch (Exception e) {
            throw new ServiceException("调用base服务失败", e);
        }
    }


    /**
     * 获取7个时间段/8个时间点
     *
     * @param startTime
     * @param endTime
     * @return
     */
    private Map<Integer, Long> getTimesampInterval(Long startTime, Long endTime) {
        Long samp = endTime - startTime;
        if (samp < 0) {
            throw new ServiceException("时间参数传入有误", RestConst.ErrorCode.SERVICE_FAIL);
        }
        Long a = samp / 7; //除以7的整数
        Map<Integer, Long> param = new HashMap<>();
        param.put(1, startTime);
        param.put(2, startTime + a);
        param.put(3, startTime + (2 * a));
        param.put(4, startTime + (3 * a));
        param.put(5, startTime + (4 * a));
        param.put(6, startTime + (5 * a));
        param.put(7, startTime + (6 * a));
        param.put(8, endTime);
        return param;
    }

    /**
     * 获取需要的时间戳
     *
     * @param type 1昨天零点 2今天零点 3本周第一天零点 4七天前零点 5一个月前零点 6三个月前零点
     * @return
     */
    private static Long getTimesamp(int type) {
        if (type == 3) {
            Calendar cal = Calendar.getInstance();
            cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
            cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
            cal.set(Calendar.MILLISECOND, 0);
            return cal.getTimeInMillis();
        }

        Calendar cal = Calendar.getInstance();
        switch (type) {
            case 1:
                cal.add(Calendar.DATE, -1);
                break;
            case 4:
                cal.add(Calendar.DATE, -7);
                break;
            case 5:
                cal.add(Calendar.MONTH, -1);
                break;
            case 6:
                cal.add(Calendar.MONTH, -3);
                break;
        }
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTimeInMillis();
    }


    //map按照value排序[倒序]
    private static Map sortMap(Map oldMap) {
        ArrayList<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(oldMap.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> arg0,
                               Map.Entry<String, Integer> arg1) {
                return arg0.getValue() - arg1.getValue();
            }
        });
        Map newMap = new LinkedHashMap();
        for (int i = list.size() - 1; i >= 0; i--) {
            newMap.put(list.get(i).getKey(), list.get(i).getValue());
        }
        return newMap;
    }

    public Object initCountOrder(Long companyID) {
        CountOrder countOrder1 = new CountOrder();
        countOrder1.setId(companyID);
        countOrder1.setTotalAmount((BigDecimal.ZERO));
        countOrder1.setOrderCount(0);
        countOrder1.setUpdateTime(CommonUtils.getCurTimestamp());
        countOrder1.setCompanyID(companyID);
        //超级管理员
        countOrderMapper.insertSelective(countOrder1);
        CountOrder countOrder2 = new CountOrder();
        countOrder2.setId(Long.parseLong(companyID.toString().substring(0, companyID.toString().length() - 1)));
        countOrder2.setTotalAmount((BigDecimal.ZERO));
        countOrder2.setOrderCount(0);
        countOrder2.setUpdateTime(CommonUtils.getCurTimestamp());
        countOrder2.setCompanyID(companyID);
        //总部
        countOrderMapper.insertSelective(countOrder2);
        return "success";
    }


    /**
     * -----------------------------------奖金发放对账单-------------------------------------
     * added by pengzh 2018-3-26
     */


    /**
     * 查询company's bonus数据
     *
     * @param oID companyID
     * @return
     */
    public Object getBonusTotal(String oID) {
        UserCommissionDto selectDto = new UserCommissionDto();//查询条件
        Map<String, BigDecimal> resultMap = new HashMap<>();
        selectDto.setCompanyID(SystemContext.getCompanyID());
        Object object = commissionDetailMapper.selectBonusTotal(selectDto);
        if (object != null) {
            resultMap = (Map<String, BigDecimal>) object;
        }
        if (resultMap.get("settle") == null) {
            resultMap.put("settle", BigDecimal.ZERO);
        }
        if (resultMap.get("notSettle") == null) {
            resultMap.put("notSettle", BigDecimal.ZERO);
        }
        return resultMap;
    }


    /**
     * 查询company's bonus 每月数据
     *
     * @param oID companyID
     * @return
     */
    public Object getBonusListByMonth(String oID) {

        SettlementForCountDto selectDto = new SettlementForCountDto();
        selectDto.setCompanyID(SystemContext.getCompanyID());
        return commissionSettlementMapper.selectSettlementSum(selectDto);

    }


}
